<template>
  <div class="design-container">
    <a-row style="padding: 10px; align-items: center">
      <div class="tit">{{ designData.name }}</div>
      <a-col :span="20">
        <a-space :size="5">
          <a-button-group>
            <template v-for="(value, type) in designData.paperTypes" :key="type">
              <a-button
                :type="curPaperType === type ? 'primary' : ''"
                @click="setPaper(type, value)"
              >
                {{ type }}
              </a-button>
            </template>
            <a-popover
              v-model:open="designData.paperPopVisible"
              title="设置纸张宽高(mm)"
              trigger="click"
            >
              <template #content>
                <a-input-group compact style="margin: 10px 10px">
                  <a-input-number
                    v-model:value="designData.paperWidth"
                    style="width: 100px; text-align: center"
                    placeholder="宽(mm)"
                  />
                  <a-input
                    style="width: 30px; border-left: 0; pointer-events: none; backgroundcolor: #fff"
                    placeholder="~"
                    disabled
                  />
                  <a-input-number
                    v-model:value="designData.paperHeight"
                    style="width: 100px; text-align: center; border-left: 0"
                    placeholder="高(mm)"
                  />
                </a-input-group>
                <a-button type="primary" style="width: 100%" @click="otherPaper">确定</a-button>
              </template>
              <a-button :type="'other' == curPaperType ? 'primary' : ''">自定义纸张</a-button>
            </a-popover>
          </a-button-group>
          <a-button type="text" :icon="h(ZoomOutOutlined)" @click="changeScale(false)"> </a-button>
          <a-input-number
            :value="designData.scaleValue"
            :min="designData.scaleMin"
            :max="designData.scaleMax"
            :step="0.1"
            disabled
            style="width: 70px"
            :formatter="(value) => `${(value * 100).toFixed(0)}%`"
            :parser="(value) => value.replace('%', '')"
          />
          <a-button type="text" :icon="h(ZoomInOutlined)" @click="changeScale(true)"></a-button>
          <a-button type="default" :icon="h(RedoOutlined)" @click="rotatePaper()">旋转</a-button>
          <a-radio-group style="width: 242px" size="small">
            <a-radio-button @click="setElsAlign('left')" title="左对齐">
              <span class="glyphicon glyphicon-object-align-left"></span>
            </a-radio-button>
            <a-radio-button @click="setElsAlign('vertical')" title="居中">
              <span class="glyphicon glyphicon-object-align-vertical"></span>
            </a-radio-button>
            <a-radio-button @click="setElsAlign('right')" title="右对齐">
              <span class="glyphicon glyphicon-object-align-right"></span>
            </a-radio-button>
            <a-radio-button @click="setElsAlign('top')" title="顶部对齐">
              <span class="glyphicon glyphicon-object-align-top"></span>
            </a-radio-button>
            <a-radio-button @click="setElsAlign('horizontal')" title="垂直居中">
              <span class="glyphicon glyphicon-object-align-horizontal"></span>
            </a-radio-button>
            <a-radio-button @click="setElsAlign('bottom')" title="底部对齐">
              <span class="glyphicon glyphicon-object-align-bottom"></span>
            </a-radio-button>
            <a-radio-button @click="setElsAlign('distributeHor')" title="横向分散">
              <span class="glyphicon glyphicon-resize-horizontal"></span>
            </a-radio-button>
            <a-radio-button @click="setElsAlign('distributeVer')" title="纵向分散">
              <span class="glyphicon glyphicon-resize-vertical"></span>
            </a-radio-button>
          </a-radio-group>
          <a-button type="primary" :icon="h(SaveOutlined)" @click="saveTemplate()">保存</a-button>
          <a-button type="primary" :icon="h(EyeOutlined)" @click.stop="handleView">预览</a-button>
          <a-button type="primary" @click.stop="print">
            打印
            <template #icon><printer-outlined /></template>
          </a-button>
          <a-popconfirm
            title="是否确认清空?"
            okType="danger"
            okText="确定清空"
            cancel-text="取消"
            @confirm="clearPaper"
          >
            <a-button type="primary" danger :icon="h(CloseOutlined)">清空</a-button>
          </a-popconfirm>
          <a-button type="primary" @click="exportTemplate()">导出模板</a-button>
          <input
            ref="uploadRef"
            style="display: none"
            type="file"
            accept=".json"
            @change="handleClick"
          />
          <a-button @click="handleUpload()"> 导入模板 </a-button>
        </a-space>
      </a-col>
    </a-row>
    <a-row style="height: calc(100vh - 56px); overflow-y: hidden">
      <a-col class="y-scroll" style="width: 230px; height: 100%; overflow-y: auto">
        <a-card style="height: 100vh">
          <a-tabs v-model:activeKey="activeKey">
            <a-tab-pane key="1" tab="组件">
              <div class="rect-printElement-types hiprintEpContainer">
                <a-row class="drag_item_title">拖拽组件列表</a-row>
                <a-row style="height: 100px">
                  <a-col :span="12" class="drag_item_box">
                    <div>
                      <a class="ep-draggable-item" tid="defaultModule.text" style>
                        <span class="glyphicon glyphicon-text-width" aria-hidden="true"></span>
                        <p class="glyphicon-class">文本</p>
                      </a>
                    </div>
                  </a-col>
                  <a-col :span="12" class="drag_item_box">
                    <div>
                      <a class="ep-draggable-item" tid="defaultModule.image" style>
                        <span class="glyphicon glyphicon-picture" aria-hidden="true"></span>
                        <p class="glyphicon-class">图片</p>
                      </a>
                    </div>
                  </a-col>
                </a-row>
                <a-row style="height: 100px">
                  <a-col :span="12" class="drag_item_box">
                    <div>
                      <a class="ep-draggable-item" tid="defaultModule.longText">
                        <span class="glyphicon glyphicon-subscript" aria-hidden="true"></span>
                        <p class="glyphicon-class">长文</p>
                      </a>
                    </div>
                  </a-col>
                  <a-col :span="12" class="drag_item_box">
                    <div>
                      <a class="ep-draggable-item" tid="defaultModule.emptyTable" style>
                        <span class="glyphicon glyphicon-th" aria-hidden="true"></span>
                        <p class="glyphicon-class">表格</p>
                      </a>
                    </div>
                  </a-col>
                </a-row>
                <a-row style="height: 100px">
                  <a-col :span="12" class="drag_item_box">
                    <div>
                      <a class="ep-draggable-item" tid="defaultModule.html" style="">
                        <span class="glyphicon glyphicon-header" aria-hidden="true"></span>
                        <p class="glyphicon-class">html</p>
                      </a>
                    </div>
                  </a-col>
                  <a-col :span="12" class="drag_item_box">
                    <div>
                      <a class="ep-draggable-item" tid="defaultModule.customText" style>
                        <span class="glyphicon glyphicon-text-width" aria-hidden="true"></span>
                        <p class="glyphicon-class">自定义</p>
                      </a>
                    </div>
                  </a-col>
                </a-row>
                <a-row class="drag_item_title">辅助</a-row>
                <a-row style="height: 100px">
                  <a-col :span="12" class="drag_item_box">
                    <div>
                      <a class="ep-draggable-item" tid="defaultModule.hline" style>
                        <span
                          class="glyphicon glyphicon-resize-horizontal"
                          aria-hidden="true"
                        ></span>
                        <p class="glyphicon-class">横线</p>
                      </a>
                    </div>
                  </a-col>
                  <a-col :span="12" class="drag_item_box">
                    <div>
                      <a class="ep-draggable-item" tid="defaultModule.vline" style>
                        <span class="glyphicon glyphicon-resize-vertical" aria-hidden="true"></span>
                        <p class="glyphicon-class">竖线</p>
                      </a>
                    </div>
                  </a-col>
                </a-row>
                <a-row style="height: 100px">
                  <a-col :span="12" class="drag_item_box">
                    <div>
                      <a class="ep-draggable-item" tid="defaultModule.rect">
                        <span class="glyphicon glyphicon-unchecked" aria-hidden="true"></span>
                        <p class="glyphicon-class">矩形</p>
                      </a>
                    </div>
                  </a-col>
                  <a-col :span="12" class="drag_item_box">
                    <div>
                      <a class="ep-draggable-item" tid="defaultModule.oval">
                        <span class="glyphicon glyphicon-record" aria-hidden="true"></span>
                        <p class="glyphicon-class">椭圆</p>
                      </a>
                    </div>
                  </a-col>
                </a-row>
                <a-row style="height: 100px">
                  <a-col :span="12" class="drag_item_box">
                    <div>
                      <a class="ep-draggable-item" tid="defaultModule.barcode">
                        <span class="glyphicon glyphicon-barcode" aria-hidden="true"></span>
                        <p class="glyphicon-class">条形码</p>
                      </a>
                    </div>
                  </a-col>
                  <a-col :span="12" class="drag_item_box">
                    <div>
                      <a class="ep-draggable-item" tid="defaultModule.qrcode">
                        <span class="glyphicon glyphicon-qrcode" aria-hidden="true"></span>
                        <p class="glyphicon-class">二维码</p>
                      </a>
                    </div>
                  </a-col>
                </a-row>
              </div>
            </a-tab-pane>
            <a-tab-pane key="2" tab="模型" force-render>
              <!-- 这里自定义显示样式 custom-style-types -->
              <div id="provider-container" class="custom-style-types"></div>
              <div v-if="loading" class="loading-wrapper">
                <span class="loading-dot loading-dot-spin"><i></i><i></i><i></i><i></i></span>
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>
      <a-col :span="15" class="y-scroll" style="height: 100%; overflow-y: auto">
        <a-card class="card-design">
          <div id="hiprint-printTemplate" class="hiprint-printTemplate"></div>
        </a-card>
      </a-col>
      <a-col
        :span="5"
        class="params_setting_container y-scroll"
        style="height: 100%; overflow-y: auto"
      >
        <a-card>
          <a-row class="hinnn-layout-sider">
            <div id="PrintElementOptionSetting"></div>
          </a-row>
        </a-card>
      </a-col>
    </a-row>
    <!-- 预览 -->
    <print-preview ref="preview" />
    <a-modal
      v-model:open="optDialog"
      title="属性配置"
      width="500px"
      @ok="handleOptOk"
      cancelText="取消"
      okText="确定"
    >
      <a-form ref="formRef" :model="controlData.formState" :label-col="labelCol">
        <a-form-item label="数据类型">
          <a-input type="text" v-model:value="controlData.controlName" disabled />
        </a-form-item>
        <template v-if="controlData.formState.controlType == 'Dict'">
          <a-form-item label="字典" name="itemKey">
            <a-select
              v-model:value="controlData.formState.itemKey"
              :options="formData.dictOptions"
              :field-names="{ label: 'ItemCaption', value: 'ItemKey' }"
              placeholder="选择字典"
              @change="handleDictChange"
            >
              <template #option="{ ItemCaption, ItemKey }">
                <span>{{ ItemKey }} &nbsp; {{ ItemCaption }}</span>
              </template>
            </a-select>
          </a-form-item>
          <a-form-item label="字段列表" name="fieldKey">
            <a-select
              v-model:value="controlData.formState.fieldKey"
              :options="formData.selectOptions"
              :field-names="{ label: 'ColumnCaption', value: 'ColumnKey' }"
              placeholder="选择字段"
              @change="handleChange"
            >
              <template #option="{ ColumnCaption, ColumnKey }">
                <span>{{ ColumnKey }} &nbsp; {{ ColumnCaption }}</span>
              </template>
            </a-select>
          </a-form-item>
        </template>
        <template v-if="controlData.formState.controlType == 'DatePicker'">
          <a-form-item label="格式" name="dateFormat">
            <a-select v-model:value="controlData.formState.dateFormat">
              <a-select-option value="">默认</a-select-option>
              <a-select-option value="M/D">M/D</a-select-option>
              <a-select-option value="MM/DD">MM/DD</a-select-option>
              <a-select-option value="YY/M/D">YY/M/D</a-select-option>
              <a-select-option value="YY/MM/DD">YY/MM/DD</a-select-option>
              <a-select-option value="YYYY/M/D">YYYY/M/D</a-select-option>
              <a-select-option value="YYYY/MM/DD">YYYY/MM/DD</a-select-option>
              <a-select-option value="YY/M/D H:m">YY/M/D H:m</a-select-option>
              <a-select-option value="YY/M/D H:m:s">YY/M/D H:m:s</a-select-option>
              <a-select-option value="YY/M/D HH:mm">YY/M/D HH:mm</a-select-option>
              <a-select-option value="YY/M/D HH:mm:ss">YY/M/D HH:mm:ss</a-select-option>
              <a-select-option value="YY/MM/DD H:m">YY/MM/DD H:m</a-select-option>
              <a-select-option value="YY/MM/DD H:m:s">YY/MM/DD H:m:s</a-select-option>
              <a-select-option value="YY/MM/DD HH:mm">YY/MM/DD HH:mm</a-select-option>
              <a-select-option value="YY/MM/DD HH:mm:ss">YY/MM/DD HH:mm:ss</a-select-option>
              <a-select-option value="YYYY/M/D H:m">YYYY/M/DD H:m</a-select-option>
              <a-select-option value="YYYY/M/D H:m:s">YYYY/M/D H:m:s</a-select-option>
              <a-select-option value="YYYY/M/D HH:mm">YYYY/M/D HH:mm</a-select-option>
              <a-select-option value="YYYY/M/D HH:mm:ss">YYYY/M/D HH:mm:ss</a-select-option>
              <a-select-option value="YYYY/MM/DD H:m">YYYY/MM/DD H:m</a-select-option>
              <a-select-option value="YYYY/MM/DD H:m:s">YYYY/MM/DD H:m:s</a-select-option>
              <a-select-option value="YYYY/MM/DD HH:mm">YYYY/MM/DD HH:mm</a-select-option>
              <a-select-option value="YYYY/MM/DD HH:mm:ss">YYYY/MM/DD HH:mm:ss</a-select-option>
              <a-select-option value="M-D">M-D</a-select-option>
              <a-select-option value="MM-DD">MM-DD</a-select-option>
              <a-select-option value="YY-M-D">YY-M-D</a-select-option>
              <a-select-option value="YY-MM-DD">YY-MM-DD</a-select-option>
              <a-select-option value="YYYY-M-D">YYYY-M-D</a-select-option>
              <a-select-option value="YYYY-MM-DD">YYYY-MM-DD</a-select-option>
              <a-select-option value="YY-M-D H:m">YY-M-D H:m</a-select-option>
              <a-select-option value="YY-M-D H:m:s">YY-M-D H:m:s</a-select-option>
              <a-select-option value="YY-M-D HH:mm">YY-M-D HH:mm</a-select-option>
              <a-select-option value="YY-M-D HH:mm:ss">YY-M-D HH:mm:ss</a-select-option>
              <a-select-option value="YY-MM-DD H:m">YY-MM-DD H:m</a-select-option>
              <a-select-option value="YY-MM-DD H:m:s">YY-MM-DD H:m:s</a-select-option>
              <a-select-option value="YY-MM-DD HH:mm">YY-MM-DD HH:mm</a-select-option>
              <a-select-option value="YY-MM-DD HH:mm:ss">YY-MM-DD HH:mm:ss</a-select-option>
              <a-select-option value="YYYY-M-D H:m">YYYY-M-D H:m</a-select-option>
              <a-select-option value="YYYY-M-D H:m:s">YYYY-M-D H:m:s</a-select-option>
              <a-select-option value="YYYY-M-D HH:mm">YYYY-M-D HH:mm</a-select-option>
              <a-select-option value="YYYY-M-D HH:mm:ss">YYYY-M-D HH:mm:ss</a-select-option>
              <a-select-option value="YYYY-MM-DD H:m">YYYY-MM-DD H:m</a-select-option>
              <a-select-option value="YYYY-MM-DD H:m:s">YYYY-MM-DD H:m:s</a-select-option>
              <a-select-option value="YYYY-MM-DD HH:mm">YYYY-MM-DD HH:mm</a-select-option>
              <a-select-option value="YYYY-MM-DD HH:mm:ss">YYYY-MM-DD HH:mm:ss</a-select-option>
            </a-select>
          </a-form-item>
        </template>
      </a-form>
    </a-modal>
  </div>
</template>
  <script setup>
import { ref, reactive, onMounted, computed, h, createVNode } from 'vue'
import { useRoute } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { hiPrintPlugin, hiprint } from 'vue-plugin-hiprint-extend'
import printPreview from './Preview.vue'
import helper from './provider-helper'
import defaultProvider from './default-etyps-provider'
import Api from '@/api/request.js'
import printFuns from './print-funs'
import wmsData from './wms-provider' // 左侧拖拽元素、模板数据
import printData from './print-data'
import panel from './panel' //使用wms-provider中的Template
import {
  EyeOutlined,
  PrinterOutlined,
  ZoomInOutlined,
  ZoomOutOutlined,
  RedoOutlined,
  SaveOutlined,
  CloseOutlined,
  ExclamationCircleOutlined,
  SelectOutlined
} from '@ant-design/icons-vue'
hiPrintPlugin.disAutoConnect() // 取消自动连接直接打印客户端
let hiprintTemplate
const route = useRoute()
const optDialog = ref(false)
let currentTarget
const formRef = ref()
const uploadRef = ref(null)
const labelCol = { style: { width: '80px' } }
const controlData = reactive({
  formState: {
    controlType: '',
    itemKey: '',
    fieldKey: '',
    dateFormat: ''
  },
  controlName: ''
})
const formData = reactive({
  dictOptions: [],
  selectOptions: []
})
const preview = ref(null)
const activeKey = ref('1')
const loading = ref(false)
// const printData = reactive({})
const designData = reactive({
  providerData: {},
  printModalType: 1,
  name: '',
  template: null,
  curPaper: {
    type: 'A4',
    width: 210,
    height: 296.6
  },
  paperTypes: {
    A3: {
      width: 420,
      height: 296.6
    },
    A4: {
      width: 210,
      height: 296.6
    },
    A5: {
      width: 210,
      height: 147.6
    },
    B3: {
      width: 500,
      height: 352.6
    },
    B4: {
      width: 250,
      height: 352.6
    },
    B5: {
      width: 250,
      height: 175.6
    }
  },
  // 自定义纸张
  paperPopVisible: false,
  paperWidth: '220',
  paperHeight: '80',
  // 缩放
  scaleValue: 1,
  scaleMax: 5,
  scaleMin: 0.5
})
const curPaperType = computed(() => {
  let type = 'other'
  let types = designData.paperTypes
  for (const key in types) {
    let item = types[key]
    let { width, height } = designData.curPaper
    if (item.width === width && item.height === height) {
      type = key
    }
  }
  return type
})
// 初始化 provider
hiprint.init({
  providers: [defaultProvider()]
})
/**
 * 设置纸张大小
 * @param type [A3, A4, A5, B3, B4, B5, other]
 * @param value {width,height} mm
 */
const setPaper = (type, value) => {
  try {
    if (Object.keys(designData.paperTypes).includes(type)) {
      designData.curPaper = { type: type, width: value.width, height: value.height }
      hiprintTemplate.setPaper(value.width, value.height)
    } else {
      designData.curPaper = { type: 'other', width: value.width, height: value.height }
      hiprintTemplate.setPaper(value.width, value.height)
    }
    hiprintTemplate.editingPanel.paperType = designData.curPaper.type
  } catch (error) {
    message.error(`操作失败: ${error}`)
  }
}
const otherPaper = () => {
  let value = {}
  value.width = designData.paperWidth
  value.height = designData.paperHeight
  designData.paperPopVisible = false
  setPaper('other', value)
}
const changeScale = (big) => {
  let scaleValue = designData.scaleValue
  if (big) {
    scaleValue += 0.1
    if (scaleValue > designData.scaleMax) scaleValue = 5
  } else {
    scaleValue -= 0.1
    if (scaleValue < designData.scaleMin) scaleValue = 0.5
  }
  if (hiprintTemplate) {
    // scaleValue: 放大缩小值, false: 不保存(不传也一样), 如果传 true, 打印时也会放大
    hiprintTemplate.zoom(scaleValue)
    designData.scaleValue = scaleValue
  }
}
const rotatePaper = () => {
  if (hiprintTemplate) {
    hiprintTemplate.rotatePaper()
  }
}
const setElsAlign = (e) => {
  hiprintTemplate.setElsAlign(e)
}
const requestData = () => {
  console.log(route)
  // 获取到请求参数
  // let data = new URLSearchParams(window.location.search)
  // let FormKey = data.get('FormKey')
  let FormKey = route.query.FormKey
  let OID = route.query.OID
  let SOID = route.query.SOID
  let TemplateName = route.query.TemplateName
  let TemplateID = route.query.query
  let TemplateVerid = route.query.TemplateVerid
  let TemplateStatus = route.query.TemplateStatus
  // 请求后台数据
  let url = 'WMS_PrintFunction'
  let params = JSON.stringify(['getBillDataInfo', FormKey, SOID, OID])
  Api.post(url, params)
    .then((res) => {
      console.log(res)
      if (res.error) {
        message.warning(res.error.error_info)
      } else {
        designData.providerData = res.data
        getProvider()
      }
    })
    .catch((error) => {
      console.log(error)
      message.error(`请求异常`)
    })
}
const updateTemplate = (template) => {
  if (hiprintTemplate) {
    try {
      hiprintTemplate.update(template)
      let value = {
        width: hiprintTemplate.editingPanel.width,
        height: hiprintTemplate.editingPanel.height
      }
      setPaper(hiprintTemplate.getPaperType(), value)
    } catch (e) {
      message.error(`更新失败: ${e}`)
    }
  }
}
const getDateTime = () => {
  var date = new Date()
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var strDate = date.getDate()
  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate
  }
  var time = year.toString() + month.toString() + strDate.toString()
  return time
}
const exportTemplate = () => {
  // 准备要导出的数据
  const data = hiprintTemplate.getJson() || {}
  // 转换为JSON字符串
  const jsonData = JSON.stringify(data)
  // 创建一个Blob对象，并设置相应的MIME类型
  const blob = new Blob([jsonData], { type: 'application/json' })
  // 创建一个指向该Blob的URL
  const url = URL.createObjectURL(blob)
  // 创建一个a标签
  const link = document.createElement('a')
  link.href = url
  let time = getDateTime()
  let fileName = `${designData.name}${time}.json`
  // 设置下载的文件名
  link.setAttribute('download', fileName)
  // 触发点击
  document.body.appendChild(link)
  link.click()
  // 清理并移除元素和对应的URL
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
}
const handleUpload = () => {
  uploadRef.value.click()
}
const handleClick = (e) => {
  const file = e.target.files[0]
  if (!file) {
    return
  }
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const jsonPanel = JSON.parse(e.target.result)
      console.log('jsonPanel', jsonPanel)
      updateTemplate(jsonPanel)
    } catch (error) {
      console.error('Failed to parse JSON', error)
      updateTemplate({})
    }
  }
  reader.readAsText(file)
}
const saveTemplate = () => {
  if (hiprintTemplate) {
    let template = JSON.stringify(hiprintTemplate.getJson() || {})
    let OID = route.query.OID
    let SOID = route.query.SOID
    // 请求后台数据
    let url = 'WMS_PrintFunction'
    console.log(hiprintTemplate.getJson())
    let params = JSON.stringify(['savePrintModel', SOID, OID, template])
    Api.post(url, params)
      .then((res) => {
        console.log(res)
        if (res.error) {
          message.warning(res.error.error_info)
        } else {
          message.success(res.data.msg)
        }
      })
      .catch((error) => {
        console.log(error)
        message.error(`请求异常`)
      })
  }
}
/**
 * 构建provider
 * 注意: 可拖拽元素必须在 hiprint.init() 之后调用
 * 调用之前 可以先 console.log($("#provider-container")) 看看是否有该 dom
 */
const buildProvider = (data, clear) => {
  // 组装 provider
  if (Array.isArray(data)) {
    let providerList = helper.createProviderList(data)
    hiprint.init({ providers: providerList })
  } else {
    let provider = helper.createProvider(data.key, data.options)
    console.log('provider', provider)
    hiprint.init({ providers: [provider] })
  }
  if (clear) {
    // eslint-disable-next-line no-undef
    $('#provider-container').empty() // 先清空, 避免重复构建
  }
  if (Array.isArray(data)) {
    // eslint-disable-next-line no-undef
    data.forEach((item) =>
      hiprint.PrintElementTypeManager.build($('#provider-container'), item.key)
    )
  } else {
    // eslint-disable-next-line no-undef
    hiprint.PrintElementTypeManager.build($('#provider-container'), data.key)
  }
  loading.value = false
}

const getProvider = (clear = true) => {
  let dataObj = designData.providerData
  designData.name = `${dataObj.caption}打印`
  let paramObj = {
    caption: dataObj.caption,
    key: dataObj.key,
    options: []
  }

  if (designData.printModalType == 1) {
    let mianTables = dataObj.tables.filter((f) => f.tableMode == 0) //主表
    let detailTables = dataObj.tables.filter((f) => f.tableMode == 1) //明细表
    let option1 = renderMainTable(mianTables)
    let option2 = renderDetailTable(detailTables, dataObj)
    paramObj.options = [...option1, ...option2]
  } else {
    let mianTables = dataObj.tables
    let option1 = renderMainTable(mianTables)
    paramObj.options = [...option1]
  }

  console.log('paramObj', paramObj)
  console.log('template', dataObj.Template)
  buildProvider(paramObj, clear)
  buildLeftElement()
  buildDesigner()
  // updateTemplate(dataObj.Template)
  updateTemplate(panel)
}
const renderMainTable = (mianTables) => {
  let optionList = []
  mianTables.forEach((t) => {
    let tObj = {
      tableMode: '', // 0: 主表; 1: 明细表
      groupName: '',
      groupKey: '',
      printElements: []
    }
    tObj.tableMode = t.tableMode
    tObj.groupName = t.caption
    tObj.groupKey = t.key
    tObj.printElements = t.columns
      .filter((f) => f.caption)
      .map((m) => {
        return {
          id: m.key,
          // type: m.type,
          type: 'text',
          title: m.caption,
          field: m.key,
          options: {
            width: 200,
            height: 20,
            textContentVerticalAlign: 'middle',
            attributeConfig: JSON.stringify(m.Format),
            formatter:
              'function(title,value,options,templateData,target){return window.hiprintFuns.GetAttributeValue(options, value)}'
          }
        }
      })
    optionList.push(tObj)
  })
  return optionList
}
const renderDetailTable = (detailTables, dataObj) => {
  let optionList = []
  let detailObj = {
    tableMode: '', // 0: 主表; 1: 明细表
    groupName: '',
    groupKey: '',
    printElements: []
  }
  detailObj.tableMode = 1
  detailObj.groupName = '明细表'
  detailObj.groupKey = `${dataObj.key}_Detail`
  detailTables.forEach((t) => {
    let cols = t.columns
      .filter((f) => f.caption)
      .map((m) => {
        return {
          checked: JSON.stringify(m.Format) != '{}',
          field: m.key,
          text: m.caption,
          title: m.caption,
          attributeConfig: JSON.stringify(m.Format),
          formatter2:
            'function(value,row,index,options){return window.hiprintFuns.GetAttributeValue(options, value, index)}'
        }
      })
    cols.unshift({
      checked: false,
      field: '',
      text: '',
      title: ''
    })
    let obj = {
      id: t.key,
      type: 'table',
      title: t.caption,
      field: t.key,
      columns: [cols],
      options: {
        field: t.key,
        fields: []
      }
    }
    obj.options.fields = cols
    detailObj.printElements.push(obj)
  })
  optionList.push(detailObj)
  return optionList
}
/**
 * 构建左侧可拖拽元素
 * 注意: 可拖拽元素必须在 hiprint.init() 之后调用
 * 而且 必须包含 class="ep-draggable-item" 否则无法拖拽进设计器
 */
const buildLeftElement = () => {
  // eslint-disable-next-line no-undef
  hiprint.PrintElementTypeManager.buildByHtml($('.ep-draggable-item'))
}
/**
 * 构建设计器
 * 注意: 必须要在 onMounted 中去构建
 * 因为都是把元素挂载到对应容器中, 必须要先找到该容器
 */
const buildDesigner = () => {
  // eslint-disable-next-line no-undef
  $('#hiprint-printTemplate').empty() // 先清空, 避免重复构建
  hiprintTemplate = new hiprint.PrintTemplate({
    // template: panel,
    settingContainer: '#PrintElementOptionSetting', // 元素参数容器
    onAttributeChooseClick: (target) => {
      // 测试 3秒后修改图片地址值
      // console.log(target)
      currentTarget = target
      openOpt(target.getValue())
      // target.setValue(11111)
      // target.getValue()
      // target.refresh(1111)
    },
    onDataChanged: (type, json) => {
      console.log(type) // 新增、移动、删除、修改(参数调整)、大小、旋转
      // console.log(json) // 返回 template
      console.log(hiprintTemplate.getJson()) // 返回 template
    },
    onUpdateError: (e) => {
      console.log(e)
    }
  })
  // 构建 并填充到 容器中
  // 可以先 console.log($("#hiprint-printTemplate")) 看看是否有该 dom
  hiprintTemplate.design('#hiprint-printTemplate', { grid: true })
}
const getControlName = (param) => {
  let name = param
  switch (param) {
    case 'TextEditor':
      name = '文本'
      break
    case 'Dict':
      name = '字典'
      break
    case 'ComboBox':
      name = '单选列表'
      break
    case 'DatePicker':
      name = '日期'
      break
    case 'NumberEditor':
      name = '数值'
      break
  }
  return name
}
// 属性配置
const openOpt = (config) => {
  console.log('config：', config)
  controlData.formState = JSON.parse(config)
  // Object.assign(controlData.formState, JSON.parse(config))
  controlData.controlName = getControlName(controlData.formState.controlType)
  if (controlData.formState.controlType == 'Dict') {
    getItemKeys()
  }
  optDialog.value = true
}
const handleOptOk = () => {
  currentTarget.refresh(JSON.stringify(controlData.formState))
  controlData.formState = {}
  optDialog.value = false
  resetForm()
}
const getItemKeys = () => {
  // 请求后台数据
  let url = 'WMS_PrintFunction'
  let params = JSON.stringify(['getItemKeys'])
  Api.post(url, params)
    .then((res) => {
      formData.dictOptions = res.data
      getItemInfo()
    })
    .catch((error) => {
      console.log(error)
    })
}
const getItemInfo = () => {
  // 请求后台数据
  let url = 'WMS_PrintFunction'
  let params = JSON.stringify(['getItemInfo', controlData.formState.itemKey])
  Api.post(url, params)
    .then((res) => {
      formData.selectOptions = res.data
    })
    .catch((error) => {
      console.log(error)
    })
}
const handleDictChange = (value) => {
  console.log(`selected ${value}`)
  controlData.formState.itemKey = value
}
const handleChange = (value) => {
  console.log(`selected ${value}`)
  controlData.formState.fieldKey = value
}
const resetForm = () => {
  formRef.value.resetFields()
}
// 预览
const handleView = () => {
  // console.log('printData：', printData)
  preview.value.show(hiprintTemplate, printData)
}
/**
 * 浏览器打印
 */
const print = () => {
  // 打印数据，key 对应 元素的 字段名
  // let printData = { name: 'CcSimple' }
  // 参数: 打印时设置 左偏移量，上偏移量
  let options = { leftOffset: -1, topOffset: -1 }
  // 扩展
  let ext = {
    callback: () => {
      console.log('浏览器打印窗口已打开')
    }
    // styleHandler: () => {
    //   // 重写 文本 打印样式
    //   return '<style>.hiprint-printElement-text{color:red !important;}</style>'
    // }
  }
  // 调用浏览器打印
  hiprintTemplate.print(printData, options, ext)
}
const clearPaper = () => {
  try {
    hiprintTemplate.clear()
  } catch (error) {
    message.error(`操作失败: ${error}`)
  }
}
/**
 * 这里必须要在 onMounted 中去构建 左侧可拖拽元素 或者 设计器
 * 因为都是把元素挂载到对应容器中, 必须要先找到该容器
 */
onMounted(() => {
  window.hiprintFuns = printFuns
  window.hiprint.query = route.query
  designData.printModalType = route.query.PrintModalType
  // requestData()
  window.hiprint.hiprintExpData = printData.hiprintExpData
  designData.providerData = wmsData
  getProvider()
})
</script>
  <style lang="scss" scoped>
:deep(.ant-btn-group .ant-btn) {
  border-color: #d9d9d9;
}
:deep(.ant-card-body) {
  padding: 10px;
}
:deep(.card-design .ant-card-body) {
  padding: 24px;
}
.design-container {
  .tit {
    width: 230px;
    font-size: 16px;
    font-weight: 600;
    padding-left: 10px;
    padding-right: 10px;
    overflow: hidden;
    display: inline-block;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.y-scroll::-webkit-scrollbar {
  width: 8px;
  background-color: rgba(0, 0, 0, 0);
  border-radius: 8px;
}
.y-scroll::-webkit-scrollbar-thumb {
  border-radius: 8px;
  background-color: #ddd;
}
.drag_item_box {
  height: 100%;
  padding: 6px;
}

.drag_item_box > div {
  height: 100%;
  width: 100%;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}

.drag_item_box > div > a {
  text-align: center;
  text-decoration-line: none;
}

.drag_item_box > div > a > span {
  font-size: 28px;
}

.drag_item_box > div > a > p {
  margin: 0;
}

.drag_item_title {
  font-size: 16px;
  padding: 12px 6px 0 6px;
  font-weight: bold;
}

// build 拖拽
:deep(.hiprint-printElement-type > li > ul > li > a) {
  padding: 4px 4px;
  color: #1296db;
  line-height: 1;
  height: auto;
  text-overflow: ellipsis;
}

// 默认图片
:deep(.hiprint-printElement-image-content) {
  img {
    content: url('@/assets/logo.png');
  }
}

// 设计容器
.card-design {
  overflow: hidden;
  overflow-x: auto;
  // overflow-y: auto;
}
</style>
<style>
/* 自定义 provider 构建样式 */
.custom-style-types .hiprint-printElement-type {
  display: block;
}
.custom-style-types .hiprint-printElement-type {
  padding: 0 0 0 0;
  list-style: none;
}
.custom-style-types .hiprint-printElement-type > li > .title {
  display: block;
  padding: 4px 0px;
  color: rgb(0, 58, 230);
  clear: both;
}
.custom-style-types .hiprint-printElement-type > li > ul {
  padding: 0 0 0 0;
  /* display: block; */
  display: flex;
  flex-wrap: wrap;
  list-style: none;
}
.custom-style-types .hiprint-printElement-type > li > ul > li {
  display: block;
  width: calc(calc(100% / 2) - 5px);
  /* float: left; */
  /* max-width: 105px; */
  margin-bottom: 7px;
  margin-right: 10px;
}
.custom-style-types .hiprint-printElement-type > li > ul > li:nth-child(even) {
  margin-right: 0;
}
.custom-style-types .hiprint-printElement-type > li > ul > li > a {
  padding: 12px 6px;
  color: #1296db;
  text-decoration: none;
  background: #fff;
  border: 1px solid #ddd;
  /* margin: 5px; */
  width: 100%;
  display: inline-block;
  text-align: center;
  /* margin-bottom: 7px; */
  box-sizing: border-box;
  border: 1px solid rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  box-shadow: 0 1px 0 0 rgba(0, 0, 0, 0.15);
  /* height: auto; */
  /* padding: 10px; */
  /* margin-left: 0; */
  overflow: hidden;
  line-height: 1;
  color: #1296db;
  text-align: center;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.ant-radio-group-small .ant-radio-button-wrapper {
  height: 24px;
  padding: 0 7px;
  line-height: 22px;
}
</style>
  